package com.itheima.goods.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.goods.dao.GoodsMapper;
import com.itheima.goods.pojo.Goods;
import com.itheima.goods.service.GoodsService;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsMapper goodsMapper;


    @GetMapping()
    public Result findAll(){
        List<Goods> list = goodsService.list();
        return new Result(true, StatusCode.OK,"查询成功",list);
    }
    @PostMapping()
    public Result add(@RequestBody Goods goods){

        goodsService.save(goods);
        return new Result(true,StatusCode.OK,"增加成功");
    }
    @GetMapping("/search/{page}/{size}")
    public Result findPage(@PathVariable("page")Integer page,@PathVariable("size")Integer size){
        Page<Goods> goodsPage = new Page<>(page, size);
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        Page<Goods> goodsPage1 = goodsMapper.selectPage(goodsPage, goodsQueryWrapper);
        List<Goods> list = goodsPage1.getRecords();
        return new Result(true,StatusCode.OK,"查询成功",list);
    }
    @PostMapping("/search/{page}/{size}")
    public Result findPage(@PathVariable("page")Integer page,@PathVariable("size")Integer size,@RequestBody Object object){
        Page<Goods> goodsPage = new Page<>(page, size);
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        Page<Goods> goodsPage1 = goodsMapper.selectPage(goodsPage, goodsQueryWrapper);
        List<Goods> list = goodsPage1.getRecords();
        return new Result(true,StatusCode.OK,"查询成功",list);
    }
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id")Integer id){
        Goods goods = goodsService.getById(id);
        return new Result(true,StatusCode.OK,"查询成功",goods);
    }
    @PutMapping("/{id}")
    public Result update(@PathVariable("id")Integer id,@RequestBody Goods goods){
        LambdaQueryWrapper<Goods> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Goods::getId,id);
        boolean update = goodsService.update(goods, wrapper);
        if (update){
            return new Result(true,StatusCode.OK,"更新成功");
        }else {
            return new Result(false,StatusCode.ERROR,"更新失败");
        }

    }
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id")Integer id){
        goodsService.removeById(id);
        return new Result(true,StatusCode.OK,"删除成功");
    }


}
